<template>
	<view class="login-container">
		<!-- 提示登录的图标 -->
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<!-- 登录按钮 -->
		<button type="primary" class="btn-login" @click="getUserInfo">一键登录</button>
		<!-- 登录提示 -->
		<view class="tips-text">登录后尽享更多权益</view>
	</view>
</template>

<script setup>
	import {
		useUserStore
	} from '@/store/user';
	const userStore = useUserStore()
	const getToken = (info) => {
		uni.login({
			success(res) {
				const query = {
					code: res.code,
					encryptedData: info.encryptedData,
					iv: info.iv,
					rawData: info.rawData,
					signature: info.signature
				}
				login(query)
			},
			fail(err) {
				uni.$showError('登录失败！')
			}
		})
	}
	const login = async(query) => {
		const {
			data: loginResult
		} = await uni.$http.post('/api/public/v1/users/wxlogin', query)

		// console.log(loginResult)
		if (loginResult.meta.status !== 200){
			const token = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo'
			userStore.updateToken(token)
			navigateBack()
			return uni.$showMsg('登录成功')
		}
	}
	const getUserInfo = () => {
		uni.getUserProfile({
			desc: '请求授权', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: (res) => {
				// 这部分是更新用户信息的
				userStore.updateUserInfo(res.userInfo)
				getToken(res)
			},
			fail: (err) => {
				// console.log(err)
				if (e.detail.errMsg === 'getUserInfo:fail auth deny') {
					return uni.$showMsg("已取消登录授权")
				}
			}
		})
	}
	const navigateBack = () => {
		if(userStore.redirectInfo && userStore.redirectInfo.openType === 'switchTab'){
			uni.switchTab({
				url:userStore.redirectInfo.from,
				complete() {
					userStore.updateRedirectInfo({})
				}
			})
		}
	}
</script>

<style lang="scss" scoped>
	.login-container {
		height: 750rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #f8f8f8;
		position: relative;
		overflow: hidden;

		&::after {
			content: '';
			display: block;
			position: absolute;
			width: 100%;
			height: 40px;
			left: 0;
			bottom: 0;
			background-color: white;
			border-radius: 100%;
			transform: translateY(50%);
		}

		.btn-login {
			width: 90%;
			border-radius: 100px;
			margin: 15px 0;
			background-color: #c00000;
		}

		.tips-text {
			font-size: 12px;
			color: gray;
		}
	}
</style>